package models

import (
	"gitchina/kly_mall/errors"
	"gitchina/kly_mall/protobuf"
	"gitchina/kly_mall/util"

	"github.com/golang/protobuf/proto"
)

const (
	FUNC_AUTHENTICATE = "auth.authenticate"
)

func Authenticate(token string) (pass bool, mbrId, phone, nickName string) {
	var e error
	var jsond []byte
	var err errors.Error

	defer func() {
		if err != nil {
			util.WriteLog(err)
		}
	}()

	redis := util.NewRedis(RedisAddr())
	if resp := redis.Cmd("get", token); resp.Err == nil {
		var pm protobuf.Member
		if jsond, e = resp.Bytes(); e != nil {
			err = errors.New(FUNC_AUTHENTICATE, e.Error()).Append("token", token)
			return
		}
		if e = proto.Unmarshal(jsond, &pm); e == nil {
			pass = true
			mbrId = pm.Id    // string(session.MemberInfo.Id)
			phone = pm.Phone // session.MemberInfo.Phone
			nickName = pm.NickName
		} else {
			err = errors.New(FUNC_AUTHENTICATE, e.Error()).Append("token", token)
		}
	} else {
		err = errors.New(FUNC_AUTHENTICATE, resp.Err.Error()).Append("token", token)
	}
	return
}
